package com.Controller;
import org.springframework.ui.Model;
import com.Service.CartService;
import com.Service.ProductService;
import com.Service.CartService;

import com.pojo.CartItemVO;
import com.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/front/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping
    public String viewCart(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user.getId() == null) return "redirect:/front/login";

        List<CartItemVO> cartItemList = cartService.getCartItems(user.getId());
        model.addAttribute("cartItemList", cartItemList);
        return "front/cart";
    }

    @PostMapping("/add")
    public String addToCart(@RequestParam Long productId, @RequestParam Long quantity, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user.getId() == null) return "redirect:/front/login";

        cartService.addToCart(user.getId(), productId, quantity);
        return "redirect:/front/cart";
    }

    @PostMapping("/update")
    public String updateCart(@RequestParam("productIds") List<Long> productIds,
                             @RequestParam("quantities") List<Long> quantities,
                             HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user.getId() == null) return "redirect:/front/login";

        for (int i = 0; i < productIds.size(); i++) {
            cartService.updateCartItem(user.getId(), productIds.get(i), quantities.get(i));
        }
        return "redirect:/front/cart";
    }

    @GetMapping("/remove")
    public String removeFromCart(@RequestParam Long productId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user.getId() == null) return "redirect:/front/login";

        cartService.removeFromCart(user.getId(), productId);
        return "redirect:/front/cart";
    }
}
